<?php
include './include/common.inc.php';
if($mkorder){
    if (!$U['uid']) {
        $help->showmessage("请先登陆");
    }

    if (!is_array($commo)) {
        $help->showmessage("没有检查到合法的购物请求");
    }
    $t_price = 0;
    $items = array();
    foreach ($commo as $v) {
        $q = $db->fetch_first("select * from commo where id={$v['id']}");
        if ($q) {
            if (($q['stock'] - $v['count']) < 0) {
                $help->showmessage("您所购买的 {$q['name']} 数量不足{$v['count']}，库存还剩{$q['stock']}件，请返回购物车修改数量", $C['SITE_URL'] . '/cart.php');
            }
            if ($q['discount'] > 0) {
                $t_price = $t_price + ($q['vprice'] * $v['count'] * $q['discount'] / 10);
            } else {
                $t_price = $t_price + $q['vprice'] * $v['count'];
            }
            $items[] = array('id'=>$q['id'],"count"=>$v['count']);
        }
        
    }
    foreach($items as $v){
        $q=$db->fetch_first("select stock from commo where id = {$v['id']}");
        $newstock=max(0,($q['stock']-$v['count']));
        $db->query("update commo set stock={$newstock} where id ={$v['id']}");
    }
    $item = serialize($items);
    $nowtime = time();
    $db->query("INSERT INTO `order` (uid,item,price,time) VALUES ({$U['uid']},'{$item}',{$t_price},{$nowtime})");
    
    setcookie("buycommo",null,-1,'/');
    
    header('Location:'.$C['SITE_URL'].'/order.php?id='.$db->insert_id());

    exit;
}
$cookie=$_COOKIE['buycommo'];
$commos=array();
if($cookie){
    $arr=unserialize(stripslashes($cookie));
    if($arr){
        foreach ($arr as $k=>$v){
            $q=$db->fetch_first("select * from commo where id={$k}");
            if($q){
                $q['count']=$v;
                $commos[]=$q;
            }
        }
    }
}
$tpl->assign('title','我的购物车');
$tpl->assign("commos",$commos);
$tpl->display("cart.html");

